﻿using CsharpHttpHelper;
using CsharpHttpHelper.Enum;
using Dapper;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Net;
using System.Threading;
using System.Threading.Tasks;

namespace DotnetSpider.Lawyee.Src
{
	//public class TimedBackgroundService : BackgroundService
	//{
	//	private Timer _timer;

	//	public TimedBackgroundService()
	//	{
	//	}

	//	protected override async Task ExecuteAsync(CancellationToken stoppingToken)
	//	{
	//		_timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(60));
	//		await Task.CompletedTask;
	//	}

	//	private void DoWork(object state)
	//	{
	//		LawSpider.isSchedulerEmpty = true;
	//	}

	//	public override void Dispose()
	//	{
	//		base.Dispose();
	//		_timer?.Dispose();
	//	}
	//}


	public class TimedBackgroundService : BackgroundService
	{
		public static SpiderOptions Options_;
		
		public TimedBackgroundService(SpiderOptions options_)
		{
			Options_ = options_;
		}

		private CancellationTokenSource _CancelSource;
		public async Task StartAsync()
		{
			_CancelSource = new CancellationTokenSource();
			await base.StartAsync(_CancelSource.Token);
		}

		public async Task CancelAsync()
		{
			await base.StopAsync(_CancelSource.Token);
		}

		protected override async Task ExecuteAsync(CancellationToken stoppingToken)
		{
			//while (!stoppingToken.IsCancellationRequested)
			//{
			//	await Task.Delay(30000, stoppingToken).ContinueWith(tsk =>
			//	{
			//		LawSpider.isSchedulerEmpty = true;
			//	});
			//}
			string user = Options_.user;// ConfigurationManager.AppSettings["user"];

			while (!stoppingToken.IsCancellationRequested)
			{
				await Task.Delay(1000 * 60, stoppingToken).ContinueWith(tsk =>
				{
					LawSpider.isSchedulerEmpty = true;
					DataTable dt = new DataTable();
					string cookie = string.Empty;
					using (var conn = new SqlConnection(Options_.StorageConnectionString))
					{
						//dt = DataTableToIDataReader(conn.ExecuteReader($"select * from LawOptions where id='"+ user + "' "));
						//if (dt.Rows.Count > 0)
						//{
						//	cookie = dt.Rows[0]["cookie"].ToString();
						//}
						cookie =  Options_.cookies;
						if (!string.IsNullOrEmpty(cookie))
						{
							HttpHelper http = new HttpHelper();
							WebHeaderCollection header = new WebHeaderCollection();
							header["Accept-Encoding"] = "gzip, deflate";
							header["Accept-Language"] = "zh-CN,zh;q=0.9";
							header["Connection"] = "keep-alive";
							header["X-Requested-With"] = "XMLHttpRequest";
							header["Origin"] = "http://www.faxin.cn";
				
							HttpItem item = new HttpItem()
							{
								URL = "http://www.faxin.cn/GetUserState.ashx",//URL     必需项    
								Method = "POST",//URL     可选项 默认为Get   
								PostDataType = PostDataType.String,//默认为字符串，同时支持Byte和文件方法
								PostEncoding = System.Text.Encoding.UTF8,//默认为Default，
								Accept = "*/*",
								ContentType = "application/x-www-form-urlencoded",
								Host = "www.faxin.cn",
								Referer = "http://www.faxin.cn/search/GeneralLawSearch.aspx",
								UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36",
								Header = header,
								Cookie = cookie,
							};
							HttpResult result = http.GetHtml(item);


							string newcooke = string.Empty;
							string cookie2 = HttpHelper.GetSmallCookie(result.Cookie);
							if (!string.IsNullOrEmpty(cookie2))
							{
								string[] cookies = cookie.Split(';', StringSplitOptions.RemoveEmptyEntries);
								for (int i = 0; i < cookies.Length; i++)
								{
									if (cookies[i].IndexOf("lawapp_web") >= 0)
									{
										cookies[i] = cookie2;
									}
									newcooke += cookies[i] + ";";
								}
								//conn.Execute($"update LawOptions set cookie = '" + newcooke + "' where id = '"+ user + "' ");
								Options_.cookies = newcooke;
							}


							//////
							if (newcooke == "")
							{
								newcooke = cookie;
							}
							header = new WebHeaderCollection();
							header["Accept-Encoding"] = "gzip, deflate";
							header["Accept-Language"] = "zh-CN,zh;q=0.9";
							header["Connection"] = "keep-alive";
							header["X-Requested-With"] = "XMLHttpRequest";
							header["Origin"] = "http://www.faxin.cn";

							item = new HttpItem()
							{
								URL = "http://www.faxin.cn/user/UpdateUserState.ashx?num=" + new Random().Next(0,100),
								Method = "GET",//URL     可选项 默认为Get   
								PostDataType = PostDataType.String,//默认为字符串，同时支持Byte和文件方法
								PostEncoding = System.Text.Encoding.UTF8,//默认为Default，
								Accept = "*/*",
								ContentType = "application/x-www-form-urlencoded",
								Host = "www.faxin.cn",
								Referer = "http://www.faxin.cn/search/GeneralLawSearch.aspx",
								UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36",
								Header = header,
								Cookie = newcooke,
							};
							result = http.GetHtml(item);
						}
					}


				});

				await Task.Delay(1000 * 60 * 60 * 1, stoppingToken).ContinueWith(tsk =>
				{
					FaXin.isSchedulerEmpty = true;
				});
				
			}
		}



		public static DataTable DataTableToIDataReader(IDataReader reader)
		{
			DataTable objDataTable = new DataTable("Table");
			int intFieldCount = reader.FieldCount;
			for (int intCounter = 0; intCounter < intFieldCount; ++intCounter)
			{
				objDataTable.Columns.Add(reader.GetName(intCounter).ToUpper(), reader.GetFieldType(intCounter));
			}
			objDataTable.BeginLoadData();
			object[] objValues = new object[intFieldCount];
			while (reader.Read())
			{
				reader.GetValues(objValues);
				objDataTable.LoadDataRow(objValues, true);
			}
			reader.Close();
			objDataTable.EndLoadData();
			return objDataTable;
		}
	}


}
